﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.Threading;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Services;

namespace YAPACS.RisServer.Services;

public class GroupCodeProvider(IHttpContextAccessor context, IStationCodeProvider stationCodeProvider, IRepository<Station, Guid> stationRepository)
    : DomainService, IGroupCodeProvider, ITransientDependency
{
    private readonly HttpContext _context = context.HttpContext;
    private readonly IStationCodeProvider _stationCodeProvider = stationCodeProvider;
    private readonly IRepository<Station, Guid> _stationRepository = stationRepository;

    public string GetGroupCode()
    {
        var groupCode = _context?.Request.Cookies["GroupCode"]?.ToUpperInvariant();
        if (string.IsNullOrWhiteSpace(groupCode))
        {
            var stationCode = _stationCodeProvider.GetStationCode();
            groupCode = AsyncHelper.RunSync(async () =>
            {
                var station = await _stationRepository.FindAsync(s => s.Code == stationCode);
                if (station != null)
                {
                    return station.Devices.Select(d => d.DeviceGroup).FirstOrDefault(g => g != null)?.Code;
                }
                return null;
            });
        }
        return groupCode;
    }
}
